<?php
namespace App\Services;
use App\Models\Balance;
use App\Models\User;

class BalanceService {

    public static function store($user_id, $amount, $type, $order_id, $is_transaction = true) {
        try {
            $is_transaction && \DB::beginTransaction();
            $user = User::lockForUpdate()->find($user_id);
            if ($user) {
                $balanceModel = Balance::where('user_id', $user_id)->orderBy('id', 'desc')->first();
                $balance = ($balanceModel->balance ?? 0) + $amount;
                Balance::create([
                    'order_id' => $order_id,
                    'user_id' => $user_id,
                    'type' => $type,
                    'amount' => $amount,
                    'balance' => $balance
                ]);
                $user->balance = $balance;
                $user->save();
            }
            $is_transaction && \DB::commit();
        } catch (\Exception $e) {
            $is_transaction && \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }

}
